﻿using System.Windows;
using System.Windows.Controls;
using TextAnalytics.Models;

namespace TextAnalytics.Views
{
    /// <summary>
    /// Interaction logic for ProjectTreeView.xaml
    /// </summary>
    public partial class ProjectTreeView : UserControl
    {
        public ProjectTreeView()
        {
            InitializeComponent();
        }

        private void ProjectTreeView_Loaded(object sender, RoutedEventArgs e)
        {
            ProjectTree.Items.Clear();
            ProjectService.Default.DidOpenProject += ProjectService_DidLoadProject;
            ProjectService.Default.DidCloseProject += ProjectService_DidCloseProject;
        }

        void ProjectService_DidCloseProject(ProjectService sender, System.EventArgs args)
        {
            ProjectTree.Items.Clear();
        }

        private void ProjectService_DidLoadProject(ProjectService sender, OpenProjectEventArgs eventArgs)
        {
            TraverseDirectory(eventArgs.OpenProject.RootDirectory, ProjectTree.Items);
        }

        private void TraverseDirectory(DirectoryModel directory, ItemCollection parentItems)
        {
            var directoryTreeViewItem = GetTreeViewItemWithHeader(directory.Title);
            directoryTreeViewItem.Tag = directory;
            foreach (var subDir in directory.Directories)
            {
                TraverseDirectory(subDir, directoryTreeViewItem.Items);
            }
            foreach (var file in directory.Files)
            {
                TraverseFile(file, directoryTreeViewItem.Items);
            }
            parentItems.Add(directoryTreeViewItem);
        }

        private void TraverseFile(FileModel file, ItemCollection parentTreeViewItem)
        {
            var fileTreeViewNode = GetTreeViewItemWithHeader(file.Title);
            fileTreeViewNode.Tag = file;
            parentTreeViewItem.Add(fileTreeViewNode);
        }

        private TreeViewItem GetTreeViewItemWithHeader(string header)
        {
            var treeNode = new TreeViewItem();
            treeNode.Header = header;
            treeNode.Selected += treeNode_Selected;
            return treeNode;
        }

        void treeNode_Selected(object sender, RoutedEventArgs e)
        {
            var treeNode = sender as TreeViewItem;
            if (treeNode == null) return;

            var file = treeNode.Tag as FileModel;
            if (file == null) return;

            ProjectService.Default.ChangeSelectedFile(file);

            e.Handled = true;
        }
    }
}
